//
//  CameraManager.swift
//  YBProject
//
//  Created by JC on 2021/10/15.
//

import Foundation
import UIKit

/// 相片管理协议
@objc public protocol CameraMangerDelegate: NSObjectProtocol {
    // 相片选取成功
    func selectedPhoto(success img: UIImage)
    // 选取错误信息
    @objc optional func selectedPhoto(fail errMsg: String)
}

// MARK: - 外部接口
extension CameraManager {
    
    /// 选择相片
    public func selectedPhoto(_ isEdit: Bool = true) {
        self.isEdit = isEdit
        openCameraOrPhoto(type: .photo)
    }
}

final public class CameraManager: NSObject {
    
    /// 管理对象
    static public let share = CameraManager()
    /// 协议对象
    public var jcDelegate: CameraMangerDelegate?
    // 相片默认可编辑
    public var isEdit: Bool = true
    
    /// 打开相机或者相册
    private func openCameraOrPhoto(type : ImagePickerEnum) {
        let currentVc = Tools.currentViewController()
        // 编辑模式
        let imgPicker = UIImagePickerController()
        imgPicker.delegate = self
        imgPicker.allowsEditing = isEdit
        // 判断是否可以打开照相机
        switch type {
        case .photo:
            // 打开相片库
            imgPicker.sourceType = .photoLibrary
            // 去掉毛玻璃效果（解决：iOS11调起相册中的照片被导航栏遮挡）
            imgPicker.navigationBar.isTranslucent = false
            // 进入对应控制器
            DispatchQueue.main.async { currentVc.present(imgPicker, animated: true, completion: nil) }
            break
        case .camera:
            //拍照
            imgPicker.sourceType = .camera
            // 进入对应控制器
            DispatchQueue.main.async { currentVc.present(imgPicker, animated: true, completion: nil) }
            break
        default:
            break
        }
    }
}

extension CameraManager: UIImagePickerControllerDelegate,UINavigationControllerDelegate {
    
    /// 选取图片代理
    public func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        if let img = info[UIImagePickerController.InfoKey.originalImage] as? UIImage {
            jcDelegate?.selectedPhoto(success: img)
        } else {
            jcDelegate?.selectedPhoto?(fail: "选取图片异常")
        }
        // 完成后dismiss
        Tools.currentViewController().dismiss(animated: true, completion: nil)
    }
    
    // 取消头像图片设置代理
    public func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        Tools.currentViewController().dismiss(animated: true, completion: nil)
    }
}

public enum ImagePickerEnum {
    case photo
    case camera
    case other
}
